﻿using IdentityModel;
using IdentityServer4.Models;
using IdentityServer4.Validation;
using QMERP.Application.Services;
using QMERP.Domain.Dtos;
using QMERP.Infrastructure.CustomException;

namespace QMERP.WebApi
{
    public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
    {
        private readonly IUserService _userService;
        public ResourceOwnerPasswordValidator(IUserService userService)
        {
            _userService = userService;
        }
        public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            try
            {
                //根据context.UserName和context.Password与数据库的数据做校验，判断是否合法
                LoginResponse response = await _userService.SignIn(context.UserName, context.Password);
                context.Result = new GrantValidationResult(response.Id.ToString(), OidcConstants.AuthenticationMethods.Password);
            }
            catch (ApiException ex)
            {
                context.Result = new GrantValidationResult(
                TokenRequestErrors.InvalidTarget,
                ex.Message);
            }
        }
    }
}
